package com.zodiac.app.datathinking.demo;

import com.alibaba.fastjson.JSON;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service
public class DemoRetryService {

    @Retryable(value = MyRuntimeException.class, maxAttempts = 5, backoff = @Backoff(delay = 1000, multiplier = 2))
    public Object methodA(Map<String, Object> parameters) {
        log.info("++++++++++++++++++++++++ 执行方法A ++++++++++++++++++++++++");
        for (int i = 0; i < 10; i++) {
            if (Integer.valueOf(RandomStringUtils.randomNumeric(1)) > 3) {
                throw new MyRuntimeException(parameters);
            }
        }
        return "world";
    }

    @Recover
    public Object recover(MyRuntimeException e) {
        log.info("异常上下文 -> {}", JSON.toJSONString(e.getContext(), true));
        System.out.println("++++++++++++++++执行恢复机制++++++++++++++++");
        return "hello";
    }

    @Getter
    static class MyRuntimeException extends RuntimeException {
        private Map<String, Object> context;

        public MyRuntimeException(Map<String, Object> context) {
            this.context = context;
        }
    }

}
